<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <!-- 修改导入按钮，使用自定义导入功能 -->
        <a-button type="primary" preIcon="ant-design:import-outlined" @click="handleImportExcel">导入</a-button>
        <a-dropdown v-if="selectedRowKeys.value && selectedRowKeys.value.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="mdi:chevron-down" />
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'gender'">
          <span v-if="text === 1">男</span>
          <span v-else-if="text === 2">女</span>
          <span v-else>错误的测试代码</span>
        </template>
        <template v-if="column.dataIndex === 'status'">
          <span v-if="text === 0" style="color: #666; font-weight: bold">未提交审核</span>
          <span v-else-if="text === 1" style="color: #ff8c00; font-weight: bold">审核中</span>
          <span v-else-if="text === 2" style="color: #52c41a; font-weight: bold">通过审核</span>
          <span v-else-if="text === 3" style="color: #ff4d4f; font-weight: bold">未通过审核</span>
          <span v-else style="color: #666; font-weight: bold">未知状态</span>
        </template>
        <template v-if="column.dataIndex === 'flowId'">
          <span>{{ record.flowId || '无合同ID' }}</span>
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <NurseuserProfileModal ref="registerModal" @success="handleSuccess" />
    <!-- 审核模态框 -->
    <AuditModal @register="registerAuditModal" @success="handleSuccess" />
    <!-- 隐藏的文件输入框 -->
    <input ref="fileInputRef" type="file" accept=".xlsx,.xls" style="display: none" @change="handleFileChange" />
  </div>
</template>

<script lang="ts" name="nurseuser_profile-nurseuserProfile" setup>
  import { ref, reactive, computed } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import NurseuserProfileModal from './components/NurseuserProfileModal.vue';
  import AuditModal from './components/AuditModal.vue';
  import { columns, searchFormSchema, superQuerySchema } from './NurseuserProfile.data';
  import { list, listByType, deleteOne, batchDelete, getImportUrl, getExportUrl } from './NurseuserProfile.api';
  // import { downloadFile } from '/@/utils/common/renderUtils';
  // import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { defHttp } from '/@/utils/http/axios';
  import { useRoute } from 'vue-router';
  // 引入SheetJS
  import * as XLSX from 'xlsx';
  const { createMessage } = useMessage();
  const route = useRoute();
  
  // 检测URL是否有type=1参数
  const hasTypeParam = computed(() => route.query.type === '1');
  const queryParam = reactive<any>({});
  // const checkedKeys = ref<Array<string | number>>([]);
  // const userStore = useUserStore();
  // 添加文件输入框引用
  const fileInputRef = ref<HTMLInputElement | null>(null);

  // 根据路由路径动态过滤查询条件
  const filteredSearchFormSchema = computed(() => {
    // 如果路径包含 NurseuserProfileList 且没有 type=1 参数，隐藏医院和医院名称查询条件
    if (route.path.includes('NurseuserProfileList') && route.query.type !== '1') {
      return searchFormSchema.filter(item => 
        item.field !== 'hospital' && item.field !== 'hospitalname'
      );
    }
    return searchFormSchema;
  });

  //注册model
  const registerModal = ref();
  //注册审核模态框
  const [registerAuditModal, { openModal: openAuditModal }] = useModal();
  //注册table数据
  const { tableContext, onExportXls } = useListPage({
    tableProps: {
      title: '医护端护工报名表',
      api: (params) => listByType(params, hasTypeParam.value),
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: filteredSearchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 200,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '医护端护工报名表',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 审核
   */
  function handleAudit(record) {
    // 检查审核状态，如果已通过审核则禁止再次审核
    if (record.status === 2) {
      createMessage.warning('该记录审核已通过，禁止重复提交！');
      return;
    }

    openAuditModal(true, {
      record,
    });
  }
  /**
   * 查看合同
   */
  async function handleViewContract(record) {
    console.log('查看合同，记录信息:', record);
    try {
      // 检查是否有flow_id
      if (record.flowId) {
        // 有flow_id时，直接查询合同文件并预览
        createMessage.loading('正在获取合同文件...', 2);
        console.log('请求参数 flowId:', record.flowId);

        // 使用更可靠的请求方式
        const response = await defHttp.get({
          url: '/tencent_esign/tencent_flowsfile/tencentFlowsFile/queryByFlowId1',
          params: {
            flowId: record.flowId
          },
          // 添加请求配置以获得更详细的错误信息
          timeout: 10000, // 10秒超时
        }, {
          isTransformResponse: true, // 确保响应被正确转换
          errorMessageMode: 'message' // 显示错误消息
        });

        // 检查响应是否为空数组
        if (Array.isArray(response) && response.length === 0) {
          createMessage.error('合同没有签署，请稍后重试');      
          return; // 终止后续操作，避免报错
        }


        // 检查响应数据结构
        let filePath = '';
        if (response && response.filePath) {
          // 响应是对象格式
          filePath = response.filePath;
        } else if (Array.isArray(response) && response.length > 0 && response[0].filePath) {
          // 响应是数组格式
          filePath = response[0].filePath;
        }

        if (filePath) {
          console.log('合同文件路径:', filePath);
          const prefixToRemove = 'c:/Program Files/nginx-1.26.0/html/dist';
          const processedPath = filePath.replace(prefixToRemove, '');
          console.log('处理后的文件路径:', processedPath);

          // 直接在新窗口中打开合同文件链接
          window.open(processedPath, '_blank');
          createMessage.success('合同文件已在新窗口中打开');
        } else {
          console.warn('未找到合同文件路径');
          createMessage.error('未找到合同文件');
        }
      } else {
        // 没有flow_id时，提示未签署合同
        console.warn('该记录没有flowId，无法查看合同');
        createMessage.warning('未签署合同');
      }
    } catch (error: any) {
      console.error('查看合同失败:', error);
      // 更详细的错误信息
      if (error && error.message) {
        createMessage.error(`查看合同失败: ${error.message}`);
      } else if (error && error.toString) {
        createMessage.error(`查看合同失败: ${error.toString()}`);
      } else {
        createMessage.error('查看合同失败，请稍后重试');
      }
    }
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    const actions = [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
    ];

    // 当审核状态为通过时，显示查看合同按钮
    if (record.status === 2) {
      actions.push({
        label: '查看合同',
        onClick: handleViewContract.bind(null, record),
      });
    }

    return actions;
  }
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    const actions: any[] = [];

    // 审核按钮 - 根据审核状态显示不同的按钮
    if (record.status === 2) {
      // 已通过审核的记录显示禁用的审核按钮
      actions.push({
        label: '审核已通过',
        disabled: true,
        onClick: () => {
          createMessage.warning('该记录审核已通过，禁止重复提交！');
        },
      });
    } else {
      // 未通过审核的记录显示正常的审核按钮
      actions.push({
        label: '审核',
        onClick: handleAudit.bind(null, record),
      });
    }

    // 详情按钮
    actions.push({
      label: '详情',
      onClick: handleDetail.bind(null, record),
    });

    // 删除按钮
    actions.push({
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
        placement: 'topLeft',
      },
    });

    return actions;
  }

  /**
   * 处理导入Excel
   */
  function handleImportExcel() {
    // 触发文件选择
    if (fileInputRef.value) {
      fileInputRef.value.click();
    }
  }

  /**
   * 文件选择变更处理
   */
  function handleFileChange(event: Event) {
    const target = event.target as HTMLInputElement;
    const files = target.files;
    if (files && files.length > 0) {
      const file = files[0];
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          const workbook = XLSX.read(data, { type: 'array' });

          // 获取第一个工作表
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];

          // 将工作表转换为JSON数组
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          // 处理数据
          if (jsonData.length > 1) {
            // 第一行是标题行
            const headers = jsonData[0] as string[];
            const rows = jsonData.slice(1);

            // 转换为对象数组
            const resultArray = rows.map((row: any[]) => {
              const obj: any = {};
              headers.forEach((header, index) => {
                obj[header] = row[index] || '';
              });
              return obj;
            });

            // 处理gender字段
            let hasEmptyGender = false;
            const processedData = resultArray.map((item: any) => {
              // 检查gender字段
              if (!item.gender || item.gender.toString().trim() === '') {
                hasEmptyGender = true;
              } else if (item.gender.toString().trim() === '男') {
                item.gender = 1;
              } else if (item.gender.toString().trim() === '女') {
                item.gender = 2;
              }
              return item;
            });

            // 如果有空的gender字段，提示用户
            if (hasEmptyGender) {
              createMessage.warning('存在性别为空的数据，请检查Excel文件');
            }

            // 获取第一个数据对象并提交到接口
            if (processedData.length > 0) {
              await submitData(processedData[0]);
            } else {
              createMessage.warning('Excel文件中没有有效数据');
            }

            // 在这里处理解析后的数据
            console.log('解析的Excel数据:', processedData);
            createMessage.success(`成功导入${processedData.length}条数据${hasEmptyGender ? '，但存在性别为空的数据' : ''}`);

            // 重置文件输入框
            if (fileInputRef.value) {
              fileInputRef.value.value = '';
            }
          } else {
            createMessage.warning('Excel文件中没有数据');
          }
        } catch (error) {
          console.error('解析Excel文件出错:', error);
          createMessage.error('解析Excel文件失败');
        }
      };
      reader.readAsArrayBuffer(file);
    }
  }

  /**
   * 提交数据到接口
   */
  async function submitData(data: any) {
    try {
      createMessage.loading('正在提交数据...');

      const result = await defHttp.post(
        {
          url: 'https://anfine.huasun-healthcare.com:80/api_anhao/nurse_user/nurseUser/examineProfile',
          data: data,
        },
        {
          isTransformResponse: false,
        }
      );

      if (result?.code === 200) {
        createMessage.success('数据提交成功');
      } else {
        createMessage.error(result?.message || '数据提交失败');
      }
    } catch (error) {
      console.error('提交数据失败:', error);
      console.log('提交数据失败:', error);
      createMessage.error('提交数据失败');
    }
  }
</script>

<style scoped></style>
